#include "uart8_nb.h"

/*******************NB模块和传感器数据上传任务*************************/
static void *NB_Sensor_TASK(void)
{
    uint32_t uwRet = 0;
    int32_t atRet = 0;
    uint32_t count = 0;
    char sendData[1024];
    char gps_buffer[64];
    float pm25_value;
    
    printf("[INFO]Starting NB_Sensor_TASK!\r\n");
    
    // 初始化NB模块
    nb_mqtt_init();
    
    // 连接华为云
    atRet = nb_mqtt_conn(HWY_BROKER_ADDRESS, HWY_PORT,
                        HWY_CLIENTID, HWY_USERNAME, HWY_PASSWORD);
    
    if (atRet != AT_OK) {
        printf("[ERROR]Failed to connect to Huawei Cloud!\r\n");
        return NULL;
    }
    
    printf("[INFO]Successfully connected to Huawei Cloud!\r\n");
    
    while (1) // 持续上报数据
    {
        // 读取PM2.5传感器数据
        pm25_value = pm25_get_data();
        
        // 模拟GPS数据（如果有GPS模块，可以替换为实际读取函数）
        strcpy(gps_buffer, "116.397428,39.90923"); // 北京坐标示例
        
        /*构造传感器数据JSON格式 */
        memset(sendData, 0, sizeof(sendData));
        
        // 构造华为云IoTDA标准格式的JSON数据
        sprintf(sendData,
            "{"
            "\"services\":["
            "{"
            "\"service_id\":\"car_sensors\","
            "\"properties\":{"
            "\"pm25\":%.2f,"
            "\"gps_data\":\"%s\","
            "\"timestamp\":%lu"
            "}"
            "}"
            "]"
            "}",
            pm25_value, gps_buffer, (unsigned long)count);
        
        printf("[INFO]********************************\r\n");
        printf("[INFO]Sending data %lu: PM2.5=%.2f μg/m³, GPS=%s\r\n", 
               count, pm25_value, gps_buffer);
        printf("[INFO]JSON: %s\r\n", sendData);
        
        // 发布数据到华为云
        uwRet = nb_mqtt_pub(HWY_PUBTOPIC, sendData);
        
        if (uwRet == AT_OK) {
            printf("[INFO]Data sent successfully!\r\n");
        } else {
            printf("[ERROR]Failed to send data, retrying...\r\n");
            osDelay(1000);
            continue;
        }
        
        // 清空接收缓冲区
        USART8_clear_rx();
        
        count++;
        
        // 每30秒上报一次数据（可根据需要调整）
        osDelay(30000);
        
        // 可以设置上报次数限制或无限循环
        // if (count > 100) break; // 可选：上报100次后停止
    }
    
    return NULL;
}

/*******************本地传感器数据监控任务*************************/
static void *Local_Sensor_TASK(void)
{
    float pm25_value = 0;
    
    while (1)
    {
        pm25_value = pm25_get_data();
        printf("[LOCAL]pm25_value: %.2f μg/m³\n", pm25_value);
        
        // 本地数据处理逻辑（可选）
        if (pm25_value > 75.0) {
            printf("[WARNING]PM2.5 level is high! Value: %.2f μg/m³\n", pm25_value);
        } else if (pm25_value > 35.0) {
            printf("[CAUTION]PM2.5 level is moderate. Value: %.2f μg/m³\n", pm25_value);
        } else {
            printf("[OK]PM2.5 level is good. Value: %.2f μg/m³\n", pm25_value);
        }
        
        osDelay(5000); // 每5秒检测一次本地数据
    }
}

/*******************程序入口函数*************************/
static void NbSensorExampleEntry(void)
{
    // 初始化UART8（NB模块通信）
    uart8_init(9600);
    
    // 初始化PM2.5传感器
    pm25_init();
    
    printf("[INFO]NB Sensor System Starting!\n");
    
    osThreadAttr_t attr;
    
    // 创建NB模块和传感器数据上传任务
    attr.name = "NB_Sensor_TASK";
    attr.attr_bits = 0U;
    attr.cb_mem = NULL;
    attr.cb_size = 0U;
    attr.stack_mem = NULL;
    attr.stack_size = 1024 * 8; // 增大栈空间
    attr.priority = osPriorityNormal;
    
    if (osThreadNew((osThreadFunc_t)NB_Sensor_TASK, NULL, &attr) == NULL)
    {
        printf("[ERROR]create NB_Sensor_TASK failed\n");
    }
    else
    {
        printf("[INFO]create NB_Sensor_TASK success\n");
    }
    
    // 创建本地传感器监控任务
    attr.name = "Local_Sensor_TASK";
    attr.stack_size = 1024 * 4;
    attr.priority = osPriorityLow; // 较低优先级
    
    if (osThreadNew((osThreadFunc_t)Local_Sensor_TASK, NULL, &attr) == NULL)
    {
        printf("[ERROR]create Local_Sensor_TASK failed\n");
    }
    else
    {
        printf("[INFO]create Local_Sensor_TASK success\n");
    }
}

APP_FEATURE_INIT(NbSensorExampleEntry);